<template>
  <div class="mui-pages" style="background-color: #fff;">
    <header class="mui-bar mui-bar-nav">
      <div class="header-common-title flex-justify-start">
        <a @click="fn.back()" href="javascript:void(0)"><img class="back-btn" src="../../../../static/images/back.png"></a>
        <div class="header-search flex-center">修改组织生活</div>
        <a @click="save()" href="javascript:void(0)" class="header-right-btn flex-center">提交</a>
      </div>
    </header>
    <div id="slider" class="mui-slider mui-fullscreen">
      <div class="mui-scroll-wrapper mui-slider-indicator mui-segmented-control mui-segmented-control-inverted">
        <div class="meeting-tab flex-justify-start">
          <a @click="tabIndex=0" :class="{'mui-active':tabIndex==0}" class="mui-control-item" href="javascript:void(0)">会议基本信息</a>
          <a @click="tabIndex=1" v-if="data.status != '0' && false" :class="{'mui-active':tabIndex==1}" class="mui-control-item" href="javascript:void(0)">记录内容</a>
          <a @click="tabIndex=2" :class="{'mui-active':tabIndex==2}" class="mui-control-item" href="javascript:void(0)">附件</a>
        </div>
      </div>
      <div class="mui-slider-group">
        <!-- ---------会议基本信息---------start -->
        <div v-show="tabIndex==0" id="meetingInfo" class="mui-slider-item mui-control-content mui-active">
          <div id="scroll1" class="mui-scroll-wrapper">
            <div class="mui-scroll record-member-lists">
              <ul class="mui-table-view meeting-editor-lists">
                <!--<li class="mui-table-view-cell flex-between-center">
                  <b><span class="mine-lists-money">·</span>标题：</b>
                  <span class="mine-lists-content">
											<input class="setup-input" type="text" v-model="data.title" placeholder="请输入标题" /></span>
                </li>-->
                <li class="mui-table-view-cell flex-between-center" id="typeSelect" @click="go('scheduleTypes')">
                  <b><span class="mine-lists-money">·</span>类型：</b>
                  <span class="mine-lists-content">
											<input class="setup-input" type="text" readonly v-model="data.typeLabel" placeholder="请选择会议类型" /></span>
                </li>
                <li class="mui-table-view-cell flex-between-center" @click="showActive()">
                  <b><span class="mine-lists-money">·</span>范围：</b>
                  <span class="mine-lists-content">
											<input class="setup-input" type="text" readonly v-model="data.scopeLabel " placeholder="请选择会议范围" /></span>
                </li>
                <li class="mui-table-view-cell flex-between-center">
                  <b><span class="mine-lists-money">·</span>主题：</b>
                  <span class="mine-lists-content">
											<input class="setup-input" type="text" v-model="data.subject" placeholder="请输入会议主题" /></span>
                </li>
                <li class="mui-table-view-cell flex-between-center">
                  <b><span class="mine-lists-money">·</span>创建人：</b>
                  <span class="mine-lists-content">{{userInfo.fullname}}</span>
                </li>
                <li @click="selectPeople('attendUserName')" class="mui-table-view-cell flex-between-center" id="joinPeople">
                  <b><span class="mine-lists-money">·</span>参与人员：</b>
                  <span class="mine-lists-content">
											<input class="setup-input" type="text" readonly v-model="data.attendUserName " placeholder="请选择参与人员" /></span>
                </li>
                <li @click="showTimePicker()" class="mui-table-view-cell flex-between-center">
                  <b><span class="mine-lists-money">·</span>会议时间：</b>
                  <span class="mine-lists-content" id="meetingTime">
											<input class="setup-input" type="text" readonly v-model="data.meetTime " placeholder="请选择会议时间" /></span>
                </li>
                <li class="mui-table-view-cell flex-between-center" @click="selectAddress()">
                  <b><span class="mine-lists-money">·</span>会议地点：</b>
                  <span class="mine-lists-content">
											<input class="setup-input" type="text" v-model="data.address" placeholder="请选择会议地点" /></span>
                </li>
                <li v-if="!isOutSide()" @click="selectPeople('compereUserName')" class="mui-table-view-cell flex-between-center">
                  <b><span class="mine-lists-money">·</span>主持人：</b>
                  <span class="mine-lists-content">
											<input class="setup-input" type="text" readonly v-model="data.compereUserName " placeholder="请输入主持人" /></span>
                </li>
                <li v-if="!isOutSide()" @click="selectPeople('recordEUserName')" class="mui-table-view-cell flex-between-center">
                  <b><span class="mine-lists-money">·</span>记录人：</b>
                  <span class="mine-lists-content">
											<input class="setup-input" type="text" readonly v-model="data.recordEUserName " placeholder="请输入记录人" /></span>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <!-- ---------会议基本信息---------end -->
        <!-- ---------记录内容-----------start -->
        <div v-if="tabIndex==1" id="recordContent" class="mui-slider-item mui-control-content">
          <div class="mui-scroll-wrapper">
            <div class="mui-scroll record-member-lists">
              <h3 class="record-item-title">记录内容：</h3>
              <div class="message-details">
                <textarea class="list-textarea" rows="5" cols="" v-model="data.recordContent"></textarea>
              </div>
              <h3 class="record-item-title">讨论内容：</h3>
              <div class="message-details">
                <textarea class="list-textarea" rows="5" cols="" v-model="data.discussContent"></textarea>
              </div>
            </div>
          </div>
        </div>
        <!-- ---------附件-----------start -->
        <div v-if="tabIndex==2" id="enclosure" class="mui-slider-item mui-control-content">
          <div class="mui-scroll-wrapper">
            <div class="mui-scroll record-member-lists">
              <p class="record-item-title">会议附件：</p>
              <ul class="mui-content-padded flex-justify-start">
                <ul class="mui-content-padded flex-justify-start">
                  <cube-upload ref="upload"
                               v-model="files"
                               action=""
                               accept="*/*"
                               :simultaneous-uploads="1"
                               @files-added="uploadFile"
                               @file-removed="fileRemoved"
                               @input="onInput">
                  </cube-upload>
                </ul>
              </ul>
            </div>
          </div>
        </div>
        <!-- ---------附件---------end -->
      </div>
    </div>
  </div>
</template>

<script>
  import tools from '@/utils/tools'
  import loginService from '@/service/loginService'
  import moment from 'moment'
  import _ from 'lodash'
  import fileIcon from '../../../../static/images/up_document.png'
  import api from '@/common/config/api'
  export default {
    components: {
    },
    data () {
      return {
        fn: tools,
        data: {
          title: '',
          address: '',
          attendUserId: '',
          attendUserName: '',
          compereUserId: '',
          compereUserName: '',
          dealFlag: '',
          meetTime: '',
          noticeFile: '',
          partyGroupId: '',
          partyGroupName: '',
          partySmallGroupId: '',
          partySmallGroupName: '',
          recordEUserId: '',
          recordEUserName: '',
          scope: '',
          scopeLabel: '',
          subject: '',
          type: '',
          typeLabel: '',
          discussContent: '',
          recordContent: '',
          isTemporary: '0', // 是否是暂存，1：是，0:否，默认是0 ,
          status: ''
        },
        tabIndex: 0,
        options: {
          pullUpLoad: true,
          scrollbar: false
        },
        userInfo: this.$store.state.userInfo,
        swipeData: [],
        attachmentList: [],
        infinite: true,
        pageIndex: 0,
        files: []
      }
    },
    created () {
      this.resumeData()
      // this.loadData()
      let arr = JSON.parse(this.data.noticeFile || '[]')
      for (let key in arr) {
        let v = arr[key]
        let url = api.downLoadFile + v.fileId
        let name = v.fileName
        let file = {"url": url, "name": v.fileName, "size": v.totalBytes}
        if (!tools.isImage(file.name)) {
          file.url = fileIcon
        }
        this.files.push(file)
        this.attachmentList.push({'fileId': v.fileId, 'fileName': v.fileName, 'totalBytes': v.totalBytes})
      }
    },
    methods: {
      go (name) {
        this.storeData()
        this.$router.push({name: name})
      },
      resumeData () {
        if (this.$store.state.scheduleEditData) {
          this.data = this.$store.state.scheduleEditData
          this.data.meetTime = tools.formateYearSecond(this.data.meetTime)
        }
        if (this.$store.state.scheduleTypeSelected) {
          let arrNames = []
          let arrKeys = []
          this.$store.state.scheduleTypeSelected.forEach((v) => {
            arrKeys.push(v.value)
            arrNames.push(v.name)
          })
          this.data.typeLabel = arrNames.join(',')
          this.data.type = arrKeys.join(',')
        }
      },
      save (routerName) {
        // 跳转页面
        let data = _.extend({}, this.data)
        let userInfo = this.$store.state.userInfo
        let strFiles = this.makeStr(this.attachmentList)
        data.noticeFile = strFiles
        data.partyGroupId = userInfo.partyMemberModel.partyGroupId
        data.partyGroupName = userInfo.partyMemberModel.partyGroupName
        data.partySmallGroupId = userInfo.partyMemberModel.partySmallGroupId
        data.partySmallGroupNam = userInfo.partyMemberModel.partySmallGroupNam
        if (data.status == 0) {
          routerName = 'schedule'
        }
        loginService.eidtInsPartyMeeting(data).then((res) => {
          if (res.code === 200) {
            this.clearStore()
            tools.tip('修改成功')
            this.$router.push({name: routerName || 'record'})
//            tools.back()
          }else {
            tools.tip(res.message)
          }
        })
      },
      isOutSide () {
        let arr = this.$store.state.scheduleTypeSelected
        if (Array.isArray(arr) && arr.length > 0 && arr[0].name.indexOf('室外') > 0) {
          return true
        }
        return false
      },
      clearStore () {
        delete this.$store.state.scheduleTypeSelected
        delete this.$store.state.scheduleEditData
        delete this.$store.state.schedulePeopleListSelectedattendUserName
        delete this.$store.state.schedulePeopleListSelectedcompereUserName
        delete this.$store.state.schedulePeopleListSelectedrecordEUserName
      },
      detail (data) {
        this.$store.state.scheduleData = data
        this.$router.push({name: 'scheduleDetail'})
      },
      openSignList (signSatus) {
        this.$router.push({'path': `/scheduleSignPeople/${signSatus}`})
      },
      // 开始签到
      startSign (meetingId) {
        loginService.startPartyMemberSign(meetingId).then((res) => {
          this.$router.push({'path': `/scheduleSign/${meetingId}`})
          if (res.code === 200) {
          }
        })
      },
      storeData () {
        this.$store.state.scheduleAddData = this.data
      },
      // 选择人员
      selectPeople (modelName) {
        if (this.data.scope === '') {
          return tools.tip('请先选择范围')
        }
        this.storeData()
        this.$router.push({path: `/schedulePeople/${modelName}`})
      },
//      会议时间格式：2019-12-06 21:48:00 精确到分
      showTimePicker () {
        this.$createTimePicker({
          minuteStep: 1,
          delay: 1,
          min: parseInt(moment().subtract(10, 'days').format('x')),
          day: {
            len: 90,
            filter: ['今天', '明天'],
            format: 'M月d日'
          },
          onSelect: (selectedTime, selectedText, formatedTime) => {
            this.data.meetTime = moment(selectedTime).format('YYYY-MM-DD HH:mm:ss')
          }
        }).show().setTime(parseInt(moment().format('x')))
      },
      // 选择会议范围
      showActive() {
        this.$createActionSheet({
          title: '会议范围',
          active: 10,
          data: [
            {
              scope: 'dzb',
              content: '支部'
            },
            {
              scope: 'dxz',
              content: '党小组'
            }
          ],
          onSelect: (item, index) => {
            this.data.scopeLabel = item.content
            this.data.scope = item.scope
          },
          onCancel: () => {
          }
        }).show()
      },
      // 选择会议地点
      selectAddress () {
        this.$createActionSheet({
          title: '会议地点',
          active: 10,
          data: [
            {
              content: '支部办公室'
            },
            {
              content: '支部活动室'
            }
          ],
          onSelect: (item, index) => {
            this.data.address = item.content
          },
          onCancel: () => {
          }
        }).show()
      },
      makeStr (arr) {
        return JSON.stringify(arr)
        let arrImg = []
        arr.forEach((v) => {
          arrImg.push(`{'fileId':'${v.fileId}','fileName':'${v.fileName}','totalBytes':${v.totalBytes}}`)
        })
        return `[${arrImg.join(',')}]`
      },
      // 删除文件
      fileRemoved (file) {
        let fileName
        let size
        if (file.name && file.size) {
          fileName = file.name
          size = file.size
        } else {
          fileName = file.file.name
          size = file.file.size
        }
        this.attachmentList.some((v, i) => {
          if (v.fileName === fileName && v.totalBytes === size) {
            this.attachmentList.splice(i, 1)
            return false
          }
        })
      },
      uploadFile (file) {
        let uploadFile = file[0]
        let formData = new FormData()
        formData.append('file', uploadFile)
        loginService.updFiles(formData).then((res) => {
          if (res.code !== 200) {
            return tools.tip(res.message)
          }
          this.attachmentList.push({'fileId': res.data[0].fileId, 'fileName': uploadFile.name, 'totalBytes': res.data[0].totalBytes})
        })
      },
      onInput (file) {
        this.$refs.upload.files.map((v) => {
          if (!tools.isImage(v.name)) {
            v.url = fileIcon
          }
          return v
        })
      },
      loadData () {
        let pkId = this.$route.params.pkId
        loginService.getPubsherMeetingInfoByPkId(pkId).then((res) => {
          if (res.code !== 200) {
            return tools.tip(res.describe === '未查询到资源' ? '已无更多数据' : res.describe)
          }
          this.data = res.data
          this.startSignKey = new Date().getTime()
          this.data.meetTime = tools.formateYearSecond(this.data.meetTime)
        })
      },
      getFilePath (str) {
        let arr = JSON.parse(str)
        arr.map((v) => {
          v.url = api.downLoadFile + v.fileId
          return v
        })
        return arr
      },
      isImage (fileName) {
        let arrExt = fileName.split('.')
        return 'PNG,JPG,JPEG,BMP,GIF'.split(',').indexOf(arrExt[arrExt.length - 1].toUpperCase()) > -1
      }
    }
  }
</script>
<style scoped="">
  .storage-btn {
    z-index:99;
  }
</style>
